package org.sparrow.user.controller;

import org.sparrow.common.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin // 启用 CORS 授权跨域请求
@RestController // 标识当前类方法返回值默认都转为 json 串 (等同与 @Controller 标识类的方法上注解 @ResponseBody)
@RequestMapping(value = "/user", produces = "application/json;charset=utf-8") // 将请求模式映射到控制器类
public class UserController {
  UserService userService;

  @Autowired // @Autowired 注解 让 Spring 完成 Bean 自动装配工作
  UserController(UserService userService) {
    this.userService = userService;
  }

  // 查询用户列表
  @GetMapping("/filter_user") // 将 HTTP GET 请求映射到方法
  // @RequestParam 解析请求参数
  public String GetUserList(
      @RequestParam(value = "username", required = false) String username,
      @RequestParam(value = "gender", required = false) Integer gender,
      @RequestParam("pageNum") int pageNum,
      @RequestParam("pageSize") int pageSize) {

    return userService.FilterUser(username, gender, pageNum, pageSize);
  }

  // 查询用户
  @GetMapping("/find_user")
  public String GetUser(@RequestParam("username") String username) {
    return userService.FindUser(username);
  }

  // 创建用户
  @PostMapping("/create_user")
  public String AddUserList(
      @RequestParam("username") String username,
      @RequestParam(value = "password", required = false) String password,
      @RequestParam(value = "realName", required = false) String realName,
      @RequestParam(value = "gender", required = false) Integer gender,
      @RequestParam(value = "birthday", required = false) String birthday) {

    return userService.CreateUser(username, password, realName, gender, birthday);
  }

  // 删除用户
  @DeleteMapping("/delete_user")
  public String DelUser(@RequestParam("username") String username) {
    return userService.DeleteUser(username);
  }

  // 更新用户
  @PutMapping("/update_user")
  public String PutUser(
      @RequestParam("username") String username,
      @RequestParam(value = "password", required = false) String password,
      @RequestParam(value = "realName", required = false) String realName,
      @RequestParam(value = "gender", required = false) Integer gender,
      @RequestParam(value = "birthday", required = false) String birthday) {

    return userService.UpdateUser(username, password, realName, gender, birthday);
  }
}
